package fumeurImpolie;
import java.util.concurrent.Semaphore;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

import javax.swing.text.StyledEditorKit.BoldAction;


public class TableSingleton {
	private static TableSingleton table = null;
	private Semaphore mutex = new Semaphore(1, true);
	public Semaphore tableVide = new Semaphore(2,true);
	private boolean ressource[] = new boolean[3];


	private TableSingleton(){
		ressource[0] = false;
		ressource[1] = false;
		ressource[2] = false;
	}
	public static synchronized TableSingleton GetInstance(){
		if(table == null){
			table = new TableSingleton();
		}
		return table;
	}
	
	public boolean VerifierIngredientDisponible(boolean[] ressourceDepart, boolean[] ressourceAcquise) throws InterruptedException{
		boolean disponible = false;
		mutex.acquire(); 
		
		for(int i = 0; i < 3 && !disponible; i++){
			disponible = (ressource[i] && !ressourceAcquise[i] && !ressourceDepart[i] );
		}
		
		if(!disponible){
			mutex.release();
		}
		return disponible;
	}
	
	public int prendreIngredient(boolean[] ressourceDepart, boolean[] ressourceAcquise){
		int index = 0;
		int compteRessource = 0;
		for(int i = 0; i < 3; i++){
			if(ressource[i] && !ressourceAcquise[i] && !ressourceDepart[i] ){
				index = i;
			}
			if(ressource[i])
				++compteRessource;
		}
		
		System.out.println("la ressource " + index + ".");
		ressource[index] = false;
		tableVide.release();
		mutex.release();
		return index;
	}
	
	public void AjouterIngredient(int ingredient1, int ingredient2) throws InterruptedException{
		mutex.acquire();
		ressource[ingredient1] = true;
		ressource[ingredient2] = true;
		System.out.println("Les ingrédients " + ingredient1 + " et " + ingredient2 + " sont déposés");
		mutex.release();
	}
	
	public void viderTable() throws InterruptedException {
		mutex.acquire();
		
		for(int i = 0 ; i < ressource.length ; ++i){
			ressource[i] = false;
		}
		
		tableVide.release(); //Compense pour l'element enlevee
		mutex.release();
	}
	public int wichResourceIsAvailable() throws InterruptedException {
		mutex.acquire();
		int index = -1;
		for(int i = 0 ; i < ressource.length ; ++i){
			if(ressource[i])
				index = i;
		}
		mutex.release();
		return index;
	}
	public boolean thereIsOnlyOneIngredient() throws InterruptedException {
		mutex.acquire();
		int compteRessource = 0;
		for(int i = 0; i < 3; i++){
			if(ressource[i])
				++compteRessource;
		}
		mutex.release();
		return compteRessource == 1;
	}
}
